// pkgPublish/pages/subject/index.js
import {
  hotTopicList,
  follow,
  cancelFollow,
  forward
} from '../../../api/ChatTopicTypeController.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    topicType: '', //热门话题ID
    userId: wx.getStorageSync('userId') || '1',
    params: {
      pageSize: 10,
      pageNum: 1
    }, //页数信息
    hotTopicList: {}, //热门话题信息
    dataCompleted: false, //数据是否加载完毕
    triggered: false, //控制下拉加载
    scrollTop: 0, //距离顶部
    isReachBottom: false, //触底节流阀
    dataCompleted: false, //数据加载完成
    playId: undefined,
    _this: undefined,
  },
  //用户下拉动作
  async onScrollRefresh() {
    try {
      this.setData({
        'params.pageNum': 1,
        dataCompleted: false
      })
      await this.getHotTopicList()
    } catch (error) {} finally {
      this.setData({
        triggered: false,
      })
    }
  },
  /**
   * 页面上拉触底事件的处理函数
   * 用户上滑动作
   */
  async onReachBottom() {
    if (this.data.isReachBottom) return
    this.setData({
      isReachBottom: true,
    })
    try {
      await this.getHotTopicList()
    } catch (error) {

    } finally {
      this.setData({
        isReachBottom: false,
      })
    }
  },
  //获取热门话题帖子列表
  async getHotTopicList() {
    if (this.data.dataCompleted) return
    const res = await hotTopicList({
      topicType: this.data.topicType,
      userId: this.data.userId,
      pageNum: this.data.params.pageNum,
      pageSize: this.data.params.pageSize,
    })
    res.chatTopicPageInfo.list = res.chatTopicPageInfo.list.map(({
      createTime,
      likeCount,
      collectCount,
      rewardSCoin,
      replyCount,
      ...item
    }) => ({
      createTime: wx.utils.formatMsgTime(createTime),
      likeCount: wx.utils.formatNumber(+likeCount),
      collectCount: wx.utils.formatNumber(+collectCount),
      rewardSCoin: wx.utils.formatNumber(+rewardSCoin),
      replyCount: wx.utils.formatNumber(+replyCount),
      ...item
    }))
    if (this.data.isReachBottom) {
      this.setData({
        'hotTopicList.chatTopicPageInfo.list': [...this.data.hotTopicList.chatTopicPageInfo.list, ...res.chatTopicPageInfo.list],
        'params.pageNum': this.data.params.pageNum + 1
      })
      if (this.data.params.pageNum > res.chatTopicPageInfo.pages) {
        this.setData({
          dataCompleted: true
        })
      }
    } else {
      this.setData({
        hotTopicList: res,
        'params.pageNum': this.data.params.pageNum + 1
      })
      if (this.data.params.pageNum > res.chatTopicPageInfo.pages) {
        this.setData({
          dataCompleted: true
        })
      }
    }
  },
  //更新帖子操作数据
  async updateStatus(ev) {
    if (ev.detail.type === 'like') {
      this.data.hotTopicList.chatTopicPageInfo.list.forEach((ele, index) => {
        if (ele.topicId === ev.detail.topicId) {
          this.setData({
            ['hotTopicList.chatTopicPageInfo.list[' + index + '].hasLike']: ev.detail.has,
            ['hotTopicList.chatTopicPageInfo.list[' + index + '].likeCount']: ev.detail.count
          })
        }
      })
    } else {
      this.data.hotTopicList.chatTopicPageInfo.list.forEach((ele, index) => {
        if (ele.topicId === ev.detail.topicId) {
          this.setData({
            ['hotTopicList.chatTopicPageInfo.list[' + index + '].hasCollect']: ev.detail.has,
            ['hotTopicList.chatTopicPageInfo.list[' + index + '].collectCount']: ev.detail.count
          })
        }
      })
    }
  },
  //控制视频播放
  play(e) {
    const id = e.detail.id
    const _this = e.detail._this
    if (!this.data.playId) {
      this.setData({
        playId: id,
        _this,
      })
    }
    if (this.data.playId && this.data.playId !== id) {
      wx.createVideoContext('video' + this.data.playId, this.data._this).pause()
      this.setData({
        playId: id,
        _this
      })
    }
  },
  //关注话题
  async topicFollow() {
    if (!wx.getStorageSync('userId')) return wx.utils.toast('请先登录!')
    if (this.data.hotTopicList.hasFollow !== '1') {
      await follow({
        userId: wx.getStorageSync('userId'),
        topicType: this.data.topicType
      })
      this.setData({
        'hotTopicList.hasFollow': '1'
      })
    } else {
      await cancelFollow({
        userId: wx.getStorageSync('userId'),
        topicType: this.data.topicType
      })
      this.setData({
        'hotTopicList.hasFollow': '0'
      })
    }
  },
  //去话题详情
  toSubjectDetail() {
    wx.navigateTo({
      url: `/pkgPublish/pages/subjectDetail/index?topicType=${this.data.topicType}`,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad({
    topicType
  }) {
    if (!topicType) {
      wx.switchTab({
        url: '/pages/index/index',
      })
    }
    this.setData({
      topicType
    })
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage']
    })
    this.getHotTopicList()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    forward(this.data.topicType)
  }
})